import Vue from 'vue'
import Vuex from 'vuex'
//import '../utils/stomp'
//import '../utils/sockjs'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import {getRequest} from "../utils/api";
import { Notification } from 'element-ui';


Vue.use(Vuex)
const now = new Date();
const store = new Vuex.Store({
    state: {
        routes: [],
        sessions: {},  //聊天会话  格式为{ ['admin#libai']:{xxxx} }
        hrs: [],  //所有用户
        currentSession: null,  //当前选中的
        currentHr: JSON.parse(window.sessionStorage.getItem("user")),  //当前登录人
        filterKey: '',
        stomp: null,
        isDot: {}
    },
    mutations :{
        //加载当前用户
        INIT_CURRENTHR(state, hr) {
            state.currentHr = hr;
        },
        //初始化路由
        inintRoutes(state,data){
              state.routes = data;
        },
        //初始选中的用户
        changeCurrentSession (state,currentSession) {
            //将红点取消
            Vue.set(state.isDot, state.currentHr.username + '#' + currentSession.username, false);
            state.currentSession = currentSession;
        },
        //添加消息
        addMessage (state,msg) {
          let mss =  state.sessions[state.currentHr.username + '#' + msg.to];
          if(!mss){
             // state.sessions[state.currentHr.username + '#' + msg.to] = [];
              //将属性加到sessions中，vue可以实时监听
              Vue.set(state.sessions, state.currentHr.username + '#' + msg.to, []);
          }
          state.sessions[state.currentHr.username + '#' + msg.to].push({
                content:msg.content,  // 发送的内容
                date: new Date(),  //发送的时间
                self:!msg.notSelf  //
            })
        },
        INIT_DATA (state) {
            //保留之前的聊天记录  防止刷新和退出浏览器将记录删除
             let data = localStorage.getItem('vue-chat-session');
             console.log(data)
             if (data) {
                 state.sessions = JSON.parse(data);
             }
        },

        INIT_HR(state,data){
              state.hrs = data;
        }
    },
    actions :{
        //接收消息
        connect(context) {
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            context.state.stomp.connect({}, success => {
                context.state.stomp.subscribe('/user/queue/chat', msg => {
                    console.log('接收消息' + msg.body)
                    let receiveMsg = JSON.parse(msg.body);
                    if (!context.state.currentSession || receiveMsg.from != context.state.currentSession.username) {
                        Notification.info({
                            title: '【' + receiveMsg.fromNickname + '】发来一条消息',
                            message: receiveMsg.content.length > 10 ? receiveMsg.content.substr(0, 10) : receiveMsg.content,
                            position: 'bottom-right'
                        })
                        Vue.set(context.state.isDot, context.state.currentHr.username + '#' + receiveMsg.from, true);
                    }
                    receiveMsg.notSelf = true;
                    receiveMsg.to = receiveMsg.from;
                    context.commit('addMessage',receiveMsg);
                })
            }, error => {

            })
        },
        initData (context) {
            context.commit('INIT_DATA');
            //获取所有用户
            getRequest('/api/chat/').then(resp=>{
                if(resp){
                    console.log("获取所有用户：" + resp);
                    context.commit('INIT_HR',resp);
                }
            })
        }
    }
})

store.watch(function (state) {
    return state.sessions
},function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
},{
    deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;